import React, { PureComponent, useEffect, useState } from "react";
import { View, StyleSheet, Text, StatusBar, SafeAreaView, BackHandler, DeviceEventEmitter, ToastAndroid } from "react-native";
import { Button, Icon, Tab, TabView } from "react-native-tengits-elements";
import { Colors, FontSize } from "../../common/Theme/TTheme";
import { scaleSize } from "../../common/Utils/ToolUtils";
import { TText } from "../../common/Widgets/WidgetDefault";
import { onlineStatus, ValidType } from "../../logic/LogicConstant";
import { TNormalExceptCircle, TNumberCircle } from "./NormalExceptCircle";
import { CircuitItem2, TSingleHoleEmptyView } from "./SubItemComponent";
import _ from 'lodash';
import Swiper from 'react-native-tengits-swiper';
import { Loop_Device_Base } from "../../libs/SerialCommon";

const CHUNKGROUP = 4;
export default class ControlSubPage extends PureComponent {
    constructor(props) {
        super(props);
        this.state={
            index:0,
        }
    }

    renderAnalys() {
        const{data, batchBtnCallback, strateyBtnCallback, disabled} = this.props;
        return <View style={{width:scaleSize(340), flexDirection:'column', justifyContent:'space-around'}}>
                <View style={styles.cardContainer}>
                    <TNormalExceptCircle title={"服务端连接"} normal={data.onlineStatus == onlineStatus.ONLINE} normalColor={Colors.normal_color} exceptColor={Colors.error_color}/>
                    {/* <TNormalExceptCircle title={"回路控制器"} normal={data.valid == ValidType.VALID} normalColor={Colors.normal_color} exceptColor={Colors.error_color}/> */}
                    <View style={{width:scaleSize(330), flexDirection:'row', justifyContent:'space-around',}}>
                        <TNumberCircle title={"洞内光强"} number={"--"} bgColor={Colors.perple_color}/>
                        <TNumberCircle title={"洞外光强"} number={"--"} bgColor={Colors.blue_color}/>
                    </View>
                </View>
                <Button buttonStyle={{paddingVertical:0, height:scaleSize(64), backgroundColor:Colors.button_color}}
                    titleStyle={{fontSize:FontSize.h4_font}}
                    title={"高级调光"} onPress={()=>{
                        if(disabled) {
                            ToastAndroid.show("当前设备离线，无法操控", ToastAndroid.SHORT);
                        } else {
                            if(data.loop && data.loop.length > 0) {
                                batchBtnCallback && batchBtnCallback(data);
                            } else {
                                ToastAndroid.show("当前设备无回路配置", ToastAndroid.SHORT);
                            }
                        }
                }}/>
                <Button buttonStyle={{paddingVertical:0, marginTop:scaleSize(28), height:scaleSize(64), backgroundColor:Colors.button_color}} 
                    titleStyle={{fontSize:FontSize.h4_font}}
                    title={"查看策略"} 
                    onPress={()=>{
                    strateyBtnCallback && strateyBtnCallback(data);
                }}/>
            </View>
    }

    sliderCallbackWrap(it, v) {
        const{data, sliderCallback,} = this.props;
        sliderCallback && sliderCallback(data, it, v);
    }

    sliderCompleteCallbackWrap(it, v) {
        const{data, sliderCompleteCallback,} = this.props;
        sliderCompleteCallback && sliderCompleteCallback(data, it, v);
    }

    renderControl(loops, deviceNumber) {
        const{disabled} = this.props;
        const chunk_data = _.chunk(loops, CHUNKGROUP);
        if((chunk_data||[]).length > 0) {
            return <Swiper key={"sw_" + deviceNumber} index={0} showsButtons={true}
                    loop={false} autoplay={false} buttonWrapperStyle={{paddingHorizontal:0}}
                    prevButton={<Icon size={scaleSize(40)} name='chevron-left' type='font-awesome' containerStyle={styles.pageBtn} color={Colors.button_color}/>}
                    nextButton={<Icon size={scaleSize(40)} name='chevron-right' type='font-awesome' containerStyle={styles.pageBtn} color={Colors.button_color}/>}
                    showsPagination={false} scrollEnabled={false}>
                    {chunk_data.map((item, ix)=>{
                        return <View key={"con_" + ix} style={{flex:1, paddingHorizontal:scaleSize(60)}}>
                            {item.map((it, i)=>{
                                return <CircuitItem2 key={`${it.loopName + "_" + i}`}
                                        containerStyle={{width:scaleSize(850)}}
                                        light={it?.loopCurrentValue} 
                                        title={it.loopName}
                                        disabled={disabled}
                                        callback={(value)=>this.sliderCallbackWrap(it, value)}
                                        slideComplete={(value)=>this.sliderCompleteCallbackWrap(it, value)}
                                        />
                            })
                    }</View>})}
            </Swiper>
        } else {
            return <View style={{flex:1, paddingHorizontal:scaleSize(60)}}>
                    <TSingleHoleEmptyView/>
                    </View>
        }
    }

    render() {
        const{data} = this.props;
        const{index} = this.state;
        const group_data = _.groupBy(data.loop||[], (item)=>Math.ceil(item.loopNumber/Loop_Device_Base));
        const keys = Object.keys(group_data);
        return <View style={{flex:1, flexDirection:'column'}}>
                {keys.length > 0 ? <Tab value={index} onChange={(i)=>{this.setState({index:i})}} indicatorStyle={{backgroundColor:Colors.button_color}}>
                    {keys.map((item, ix)=>{
                        return  <Tab.Item key={"tab_" + ix}
                                    containerStyle={{backgroundColor:'white',padding:0, height:scaleSize(90), justifyContent:'center'}} 
                                    titleStyle={{paddingVertical:0, color: ix == index ? Colors.button_color : Colors.text1_color}}
                                    icon={<Icon 
                                        name='circle' 
                                        color={(data.valid?.[item] == ValidType.VALID) ? 'green' : 'red'} 
                                        size={scaleSize(40)}/>}
                                        iconPosition={"left"}
                                        title={"回路控制器" + item} />
                    })}
                </Tab> : null}
                <View style={{flex:1, flexDirection:'row', paddingRight:scaleSize(40), paddingVertical:scaleSize(20)}}>
                    {this.renderControl(group_data[keys[index]], keys[index])}
                    {this.renderAnalys()}
                </View>
            </View>
    }
}

const styles = StyleSheet.create({
    cardContainer:{
        marginBottom:scaleSize(30),
        height:scaleSize(360),
        flexDirection:'column',
        alignItems:'center',
        justifyContent:'space-around',
        backgroundColor: Colors.white, 
        // borderWidth: 1, 
        // borderColor: Colors.white,
        borderRadius: scaleSize(6)
    },
    pageBtn:{
        justifyContent:'center',
        width:scaleSize(60), 
        height:scaleSize(200),
        // borderWidth: 1,
        // borderColor:'red'
    }
});